import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_notifier.dart';
import 'package:casdon/modules/login/data/api/login_api.dart';
import 'package:casdon/modules/login/domain/states/login_pwd_state.dart';
import 'package:casdon/modules/login/domain/usecases/login_usecase.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';

class LoginPwdNotifier extends LoginNotifier<LoginPwdState> {
  Future<void> login() async {
    if (CommonNetStatus.loading == state.status) {
      return;
    }

    if (false == state.agreed) {
      setFailure(msg: "请先同意用户协议");
      return;
    }
    state = state.copyWith(
      errorCode: null,
      message: null,
      status: CommonNetStatus.loading,
    );
    if (state.account == null || state.account!.isEmpty) {
      setFailure(msg: "请输入账号");
      return;
    }
    if (!state.account!.isPhoneNum() && !state.account!.isEmail()) {
      setFailure(msg: "账号格式不正确");
      return;
    }

    _login();
  }

  void updateAccount(String value) {
    state = state.copyWith(
      account: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  void updatePwd(String value) {
    state = state.copyWith(
      pwd: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  // 验证码登录
  void _login() async {
    setLoading();
    try {
      LoginUsecase loginUsecase = ref.read(loginUsecaseProvider);
      RequestLogin request = RequestLogin(
        grantType: LoginGrantType.password.name,
        userName: state.account,
        password: state.pwd,
      );
      final ret = await loginUsecase.execute(request);
      Log.i("验证码登录成功，token = ${ret.access_token}");

      final authStorage = ref.read(authStorageProvider.notifier);
      await authStorage.saveToken(ret.access_token);

      await ref.read(tuyaLoginProvider.notifier).login();
      final tuyaSuccess = ref.read(tuyaLoginStateProvider);
      if (!tuyaSuccess) {
        setFailure(msg: "登录失败，请稍后再试！");
        return;
      }

      setSuccess("登录成功");
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "登录失败，请稍后再试！");
    }
  }

  @override
  LoginPwdState build() {
    ref.onDispose(() {
      Log.d("已经销毁：LoginPwdNotifier");
    });
    return LoginPwdState.initial();
  }
}
